import {Buffer} from "buffer";
import {OMD} from "./OMD";
import {Data} from "./Data";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class OMDDATA implements AxdrType{

    dataCode : Buffer | null = null;
    omd : OMD | null = null;
    data : Data | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(omd : OMD, data : Data){
        this.omd = omd;
        this.data = data;
    }

    setOMD(omd : OMD){
        this.omd = omd;
    }

    setData(data : Data){
        this.data = data;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.omd = new OMD();
        codeLength += this.omd.decode(input);

        this.data = new Data();
        codeLength += this.data.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.data != null && this.omd != null){
                codeLength = 0;
                codeLength += this.data.encode(output);
                codeLength += this.omd.encode(output);
            }else{
                throw new Error("data || omd is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.omd != null && this.data) {
            return "sequence: {"+ "omd: " + this.omd + ", data: " + this.data  + "}";
        } else {
            return "omd || data is null";
        }
    }

}



